package com.mrd.gtimp.business.service;

import com.mrd.base.BaseBiz;
import com.mrd.constant.BaseTypeConstant;
import com.mrd.constant.SystemConstants;
import com.mrd.framework.utils.HttpUtils;
import com.mrd.gtimp.base.entity.User;
import com.mrd.gtimp.business.TrailCTAddressDTO;
import com.mrd.gtimp.business.entity.Contacter;
import com.mrd.gtimp.business.entity.Container;
import com.mrd.gtimp.business.entity.GoodAddress;
import com.mrd.gtimp.business.entity.Trail;
import com.mrd.spring.repository.BaseRepository;
import com.mrd.util.date.DateUtil;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

/**
 * <p> application name: gtimp <p> copyright: Copyright@2012 明睿达科技有限公司
 */

/**
 * @author luob
 */
@Service
public class TrailBiz extends BaseBiz<Trail> {

    @Resource
    private AttachmentBiz attachmentBiz;
    @Resource
    private ContainerBiz containerBiz;
    @Resource
    private ContacterBiz contacterBiz;
    @Resource
    private GoodAddressBiz goodAddressBiz;


    @Resource
    // 该处指定注入BaseRepository的dao对象
    @Qualifier("trailDao")
    public void setBaseRepository(BaseRepository<Trail, String> baseRepository) {
        super.baseRepository = baseRepository;
    }


    public void updateValidatePass(String id) throws Exception {
        User user = (User) HttpUtils.getRequest().getSession()
                .getAttribute(SystemConstants.CURRENT_USER);
        String validateDateStr = DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
        String sql = "update T_BIZ_BASE_BUSINESS set VALIDATOR_ID='" + user.getId()
                + "',  VALIDATE_TIME=to_date('" + validateDateStr
                + "','yyyy-mm-dd HH24:MI:SS') where ID='" + id + "'";
        baseRepository.updateBySql(sql);

        sql = "update T_BIZ_TRAIL set STATE = '" + BaseTypeConstant.TRAILSTATE_02 + "' where ID='"
                + id + "'";
        baseRepository.updateBySql(sql);
    }


    public List<TrailCTAddressDTO> findTrailContainers(String trailId) throws Exception {
        List<TrailCTAddressDTO> resultList = new ArrayList<TrailCTAddressDTO>();
        Trail trail = findEntityById(trailId);
        List<GoodAddress> gdes = trail.getGdes();
        Map<Container, List<GoodAddress>> ctMap = new HashMap<Container, List<GoodAddress>>();
        StringBuffer idsBuffer = new StringBuffer();
        for (GoodAddress ga : gdes) {
            String a = ga.getName();
            for (Container c : ga.getContainers()) {
                if (idsBuffer.indexOf(c.getId()) == -1) {
                    List<GoodAddress> gaList = new ArrayList<GoodAddress>();
                    gaList.add(ga);
                    ctMap.put(c, gaList);
                    idsBuffer.append(c.getId() + ",");
                } else {
                    ctMap.get(c).add(ga);
                }
            }
        }
        for (Container container : ctMap.keySet()) {
            TrailCTAddressDTO dto = new TrailCTAddressDTO();
            dto.setContainer(container);
            dto.setGoodAddresses(ctMap.get(container));
            // Set<String> set = new HashSet<String>();
            // List<String> goodsName = new ArrayList<String>();
            String gName = "";
            if (dto.getGoodAddresses() != null && dto.getGoodAddresses().size() > 0) {
                // for(GoodAddress g : dto.getGoodAddresses()) {
                // gName = g.getName();
                // set.add(gName);
                // }
                // for(String s : set) {
                // goodsName.add(s);
                // }
                gName = dto.getGoodAddresses().get(0).getName();
                dto.setGoodsName(gName);
            }
            resultList.add(dto);
        }
        return resultList;
    }


    public void updateValidateReject(String id) throws Exception {
        User user = (User) HttpUtils.getRequest().getSession()
                .getAttribute(SystemConstants.CURRENT_USER);
        String validateDateStr = DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
        String sql = "update T_BIZ_BASE_BUSINESS set VALIDATOR_ID='" + user.getId()
                + "',  VALIDATE_TIME=to_date('" + validateDateStr
                + "','yyyy-mm-dd HH24:MI:SS') where ID='" + id + "'";
        baseRepository.updateBySql(sql);

        sql = "update T_BIZ_TRAIL set STATE = '" + BaseTypeConstant.TRAILSTATE_03 + "' where ID='"
                + id + "'";
        baseRepository.updateBySql(sql);
    }


    public void updateValidateApplyCancel(String id) throws Exception {
        User user = (User) HttpUtils.getRequest().getSession()
                .getAttribute(SystemConstants.CURRENT_USER);
        String validateDateStr = DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
        String sql = "update T_BIZ_BASE_BUSINESS set VALIDATOR_ID='" + user.getId()
                + "',  VALIDATE_TIME=to_date('" + validateDateStr
                + "','yyyy-mm-dd HH24:MI:SS') where ID='" + id + "'";
        baseRepository.updateBySql(sql);

        sql = "update T_BIZ_TRAIL set STATE = '" + BaseTypeConstant.TRAILSTATE_06 + "' where ID='"
                + id + "'";
        baseRepository.updateBySql(sql);
    }


    public void updateValidateCancel(String id) throws Exception {
        User user = (User) HttpUtils.getRequest().getSession()
                .getAttribute(SystemConstants.CURRENT_USER);
        String validateDateStr = DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
        String sql = "update T_BIZ_BASE_BUSINESS set VALIDATOR_ID='" + user.getId()
                + "',  VALIDATE_TIME=to_date('" + validateDateStr
                + "','yyyy-mm-dd HH24:MI:SS') where ID='" + id + "'";
        baseRepository.updateBySql(sql);

        sql = "update T_BIZ_TRAIL set STATE = '" + BaseTypeConstant.TRAILSTATE_07 + "' where ID='"
                + id + "'";
        baseRepository.updateBySql(sql);

    }


    public void updateBizConfirm(String id) throws Exception {
        String validateDateStr = DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
        String sql = "update T_BIZ_BASE_BUSINESS set CONFIRM_TIME=to_date('" + validateDateStr
                + "','yyyy-mm-dd HH24:MI:SS') where ID='" + id + "'";
        baseRepository.updateBySql(sql);

        sql = "update T_BIZ_TRAIL set STATE = '" + BaseTypeConstant.TRAILSTATE_01 + "' where ID='"
                + id + "'";
        baseRepository.updateBySql(sql);
    }

	/*
     * (non-Javadoc)
	 * @see
	 * com.mrd.gtimp.business.biz.BaseBusinessBiz#saveBusiness(com.mrd.gtimp.business.pojo.BaseBusiness
	 * )
	 */

    public void saveBusiness(Trail trail, List<String> properties) throws Exception {
        if (null != trail) {
            // 文档
            if (trail.getSoDoc() != null
                    && (trail.getSoDoc().getId() == null || trail.getSoDoc().getId().equals(""))) {
                attachmentBiz.saveOrupdateEntity(trail.getSoDoc());
            }
            // 建立临时list存放保存过的联系人和货物列表联系人
            Set<Contacter> tempList = new HashSet<Contacter>();
            // List<Contacter> tempList = new ArrayList<Contacter>();
            // Set<Contacter> tempList = new HashSet<Contacter>();// 20140311
            // 联系人
            contacterBiz.saveConcater(trail.getShipper(), trail.getCustomer(), trail.getCreator());
            tempList.add(trail.getShipper());// 20140311

            // 保存柜
            // GoodAddress中由于柜对象不一致，保存或者修改时会发生org.hibernate.NonUniqueObjectException，
            // 所以需要先将柜取出、去重，然后重新放入GoodAddress中保证柜对象一致
            Map<String, Container> containerTmp = new HashMap<String, Container>();
            for (GoodAddress goodAddress : trail.getGdes()) {
                for (Container container : goodAddress.getContainers()) {
                    // 产生一个数据相同的container对象，这样在保存设置id时不会破会员对象，否则会使GoodAddress中的container也边为空
                    Container ctTmp = container.clone();
                    containerTmp.put(container.getId() + container.getCt_size()
                            + container.getCt_type(), ctTmp);
                }
            }
            // 保存柜之前清除该trail_id的柜
            String delContainerSql = "delete t_biz_container where trail_id = '" + trail.getId()
                    + "'";
            this.baseRepository.excuteSql(delContainerSql, null);
            // 保存柜
            for (String key : containerTmp.keySet()) {
                if (StringUtils.isNotEmpty(key)) {
                    Container container = containerTmp.get(key);
                    if (container.getSo().equals("/")) {
                        container.setSo("");
                    }
                    container.setTrail(trail);
                    // if(key.length() < 5 || "undefined".equalsIgnoreCase(key)) {
                    if (key.length() < 15 || "undefined".equalsIgnoreCase(key)) {

                        container.setId(null);
                    }

                    containerBiz.saveOrupdateEntity(container);
                } else {
                }
            }

            // Set<Contacter> conList = new HashSet<Contacter>();
            List<Contacter> conList = new ArrayList<Contacter>();
            for (GoodAddress goodAddress : trail.getGdes()) {
                // 保证柜的一致性
                List<Container> containers = new ArrayList<Container>();
                for (Container container : goodAddress.getContainers()) {
                    containers.add(containerTmp.get(container.getId() + container.getCt_size()
                            + container.getCt_type()));
                }
                goodAddress.setContainers(containers);
                // 检测是否有相同的联系人和货物联系人，如果有就不执行saveConcater
                conList.add(goodAddress.getContacter());
                conList.removeAll(tempList);
                // for(int i=0; i<tempList.size(); i++){
                // Contacter contacter = tempList.;
                for (Contacter contacter : conList) {
                    // for(Contacter contacter : tempList) {
                    if (trail.getShipper() == null
                            || !goodAddress.getContacter().getId().equals(contacter.getId())
                            || !trail.getShipper().getId().equals(contacter.getId())) {
                        // 保存地址联系人
                        contacterBiz
                                .saveConcater(goodAddress.getContacter(), trail.getCustomer(), trail
                                        .getCreator());
                        tempList.add(goodAddress.getContacter());
                    }

                }

                // 保存地址
                // goodAddressBiz.saveOrupdateEntity(goodAddress);
                goodAddress.setTrail(trail);
                if ("".equals(goodAddress.getId())) {
                    goodAddress.setId(null);
                }
            }

            // 保存拖车信息
            if (StringUtils.isEmpty(trail.getId())) {
                trail.setId(null);
                this.saveOrupdateEntity(trail);
            } else {
                // 删除原有的拖车地址重新加入
                StringBuffer sql = new StringBuffer();
                sql.append("delete from com.mrd.gtimp.business.pojo.GoodAddress g where g.trail.id = '")
                        .append(trail.getId()).append("'");
                if (trail.getGdes() != null && trail.getGdes().size() != 0) {
                    sql.append("and g.id not in (");
                    for (GoodAddress gd : trail.getGdes()) {
                        sql.append("'").append(gd.getId()).append("',");
                    }
                    sql.deleteCharAt(sql.length() - 1);
                    sql.append(")");
                }
                this.baseRepository.delete(sql.toString(), null);
                this.updateEntity(trail, properties);
            }
        }
    }


    public void updateValidatePass(String id, String validator) throws Exception {
        String validateDateStr = DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
        String sql = "update T_BIZ_BASE_BUSINESS set VALIDATOR_EXT='" + validator
                + "',  VALIDATE_TIME=to_date('" + validateDateStr
                + "','yyyy-mm-dd HH24:MI:SS') where ID='" + id + "'";
        baseRepository.updateBySql(sql);

        sql = "update T_BIZ_TRAIL set STATE = '" + BaseTypeConstant.TRAILSTATE_02 + "' where ID='"
                + id + "'";
        baseRepository.updateBySql(sql);
    }


    public void updateValidateReject(String id, String validator) throws Exception {
        String validateDateStr = DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
        String sql = "update T_BIZ_BASE_BUSINESS set VALIDATOR_EXT='" + validator
                + "',  VALIDATE_TIME=to_date('" + validateDateStr
                + "','yyyy-mm-dd HH24:MI:SS') where ID='" + id + "'";
        baseRepository.updateBySql(sql);

        sql = "update T_BIZ_TRAIL set STATE = '" + BaseTypeConstant.TRAILSTATE_03 + "' where ID='"
                + id + "'";
        baseRepository.updateBySql(sql);
    }


    public void updateValidateUpload(String id, String validator) throws Exception {
        String validateDateStr = DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
        String sql = "update T_BIZ_BASE_BUSINESS set UPLOADER_EXT='" + validator
                + "',  UPLOAD_TIME=to_date('" + validateDateStr
                + "','yyyy-mm-dd HH24:MI:SS') where ID='" + id + "'";
        baseRepository.updateBySql(sql);

        sql = "update T_BIZ_TRAIL set STATE = '" + BaseTypeConstant.TRAILSTATE_04 + "' where ID='"
                + id + "'";
        baseRepository.updateBySql(sql);
    }


    public void updateValidateFinish(String id, String validator) throws Exception {
        String validateDateStr = DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
        String sql = "update T_BIZ_BASE_BUSINESS set FINISHER_EXT='" + validator
                + "',  FINISH_TIME=to_date('" + validateDateStr
                + "','yyyy-mm-dd HH24:MI:SS') where ID='" + id + "'";
        baseRepository.updateBySql(sql);

        sql = "update T_BIZ_TRAIL set STATE = '" + BaseTypeConstant.TRAILSTATE_05 + "' where ID='"
                + id + "'";
        baseRepository.updateBySql(sql);
        System.out.println("--------------拖车id--------------" + id);
        System.out.println("--------------执行完成方法--------------");
    }

}
